package base;

/**
 * @author 何昌杰
 */
public class Base13 {

    /**
     * 合并两个排序的链表
     * 输入两个递增排序的链表，合并这两个链表并使新链表中的节点仍然是递增排序的。
     *
     * 示例1：
     *
     * 输入：1->2->4, 1->3->4
     * 输出：1->1->2->3->4->4
     * 限制：
     *
     * 0 <= 链表长度 <= 1000
     *
     */
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);


        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);

//        ListNode l1 = null;
//        ListNode l2 = new ListNode(0);
        ListNode l3 = mergeTwoLists(l1, l2);
        while (l3!= null && l3.next != null){
            System.out.print(l3.val);
            l3 = l3.next;
        }
        System.out.println();
    }

    private static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null){return l2;}
        if(l2 == null){return l1;}
        ListNode header,r;
        if(l1.val <= l2.val){
            header = r = l1;
            l1 = l1.next;
        } else {
            header = r = l2;
            l2 = l2.next;
        }
        while(l1 != null || l2 != null){
            if(l1 == null){
                r = r.next = l2;
                l2 = l2.next;
            } else if(l2 == null || l1.val <= l2.val){
                r = r.next = l1;
                l1 = l1.next;
            } else {
                r = r.next = l2;
                l2 = l2.next;
            }
        }
        return header;
    }

    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        ListNode dum = new ListNode(0), cur = dum;
        while(l1 != null && l2 != null) {
            if(l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            }
            else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        cur.next = l1 != null ? l1 : l2;
        return dum.next;
    }

}
